<template>
	<div class="hy-container">
		<HyPageHeader :title="title" :buttonData="buttonData">
			<Schedule class="mb-2.5" v-if="scheduleAndHistoryShow && processInstanceId" :processInstanceId="processInstanceId" />
			<el-collapse v-model="activeNames">
				<el-collapse-item name="1">
					<template #title>
						<div class="ml-5"><HyTitle :title="'三张清单基本信息'" /></div>
					</template>
					<div class="py-5 px-5">
						<DetailBasicInfo
							:integratedApplicationListData="integratedApplicationListData"
							:basicNameInfoData="basicNameInfoData"
							:fileListData="fileListData"
							v-if="routerParams.operateType === 'view' || routerParams.operateType === 'audit' || routerParams.operateType === 'history'"
						/>
						<BasicInfo
							:routerParams="routerParams"
							ref="basicInfoRef"
							:basicInfoData="basicInfoData"
							v-else
							:integratedApplicationListData="integratedApplicationListData"
						/>
					</div>
				</el-collapse-item>
				<el-collapse-item name="2">
					<template #title>
						<div class="ml-5"><HyTitle :title="'需求清单'" /></div>
					</template>
					<div class="py-5 px-5">
						<DemandList
							ref="demandListRef"
							:checkListData="checkListData"
							:countryData="countryData"
							:cityData="cityData"
							:pepoleData="pepoleData"
							:enterpriseData="enterpriseData"
							:substrateData="substrateData"
							:areaData="areaData"
						/>
					</div>
				</el-collapse-item>
				<el-collapse-item name="3">
					<template #title>
						<div class="ml-5"><HyTitle :title="'场景清单'" /></div>
					</template>
					<div class="py-5 px-5">
						<SceneList
							ref="sceneListRef"
							:sceneCoreListData="sceneCoreListData"
							:sceneOneLevelData="sceneOneLevelData"
							:sceneLevelFunctionData="sceneLevelFunctionData"
							:operateType="routerParams.operateType"
						/>
					</div>
				</el-collapse-item>
				<el-collapse-item name="4">
					<template #title>
						<div class="ml-5"><HyTitle :title="'改革清单'" /></div>
					</template>
					<div class="py-5 px-5">
						<ReformList :reformListData="reformListData" ref="reformListRef" />
					</div>
				</el-collapse-item>
				<el-collapse-item name="5" v-show="!scheduleAndHistoryShow">
					<template #title>
						<div class="ml-5"><HyTitle :title="'上传附件'" /></div>
					</template>
					<div class="py-5 px-5">
						<FileList ref="fileListRef" :fileListData="fileListData" />
					</div>
				</el-collapse-item>
			</el-collapse>
			<div class="mt-5"></div>
			<History v-if="scheduleAndHistoryShow && processInstanceId" :processInstanceId="processInstanceId"></History>
			<!-- 申请修改组件 -->
			<EditList @sendValue="getFileEditValue" :businessType="'1'" :businessKey="routerParams.threeListId" ref="editListRef" />
		</HyPageHeader>
		<Start ref="startRef" @submitPass="submitPass"></Start>
		<ExamineBox ref="examineBoxRef" @submitPass="submitPass"></ExamineBox>
	</div>
</template>
<script lang="ts" setup>
import HyPageHeader from '/@/components/HyPageHeader/index.vue';
import HyTitle from '/@/components/HyTitle/index.vue';
import BasicInfo from './components/BasicInfo/index.vue';
import DemandList from './components/DemandList/index.vue';
import SceneList from './components/SceneList/index.vue';
import ReformList from './components/ReformList/index.vue';
import FileList from './components/FileList/index.vue';
import { threeListSubmitApi } from '/@/api/threeList/declare';
import { useDetail } from './hooks/useDetail';
import { ElMessage, ElLoading } from 'element-plus';
import mittBus from '/@/utils/mitt';
import EditList from './components/EditList/index.vue';
import Start from '@cqdcg/admin/views/flow/form/tools/startFlow';
import ExamineBox from '@cqdcg/admin/views/flow/task/examineBox';
import Schedule from '@cqdcg/admin/views/flow/task/Schedule/index';
import History from '@cqdcg/admin/views/flow/task/History/index';
import { flowName } from '/@/constants';
import DetailBasicInfo from './components/DetailBasicInfo/index.vue';
import { useOperate } from './hooks/useOperate';

const route = useRoute();
const formType = ref('submit');
provide('formType', formType);
const {
	title,
	getDetail,
	basicInfoData,
	integratedApplicationListData,
	checkListData,
	countryData,
	cityData,
	pepoleData,
	enterpriseData,
	substrateData,
	areaData,
	reformListData,
	fileListData,
	sceneCoreListData,
	sceneOneLevelData,
	sceneLevelFunctionData,
	routerParams,
	basicNameInfoData,
	isCancel,
	isReturn,
	processInstanceId,
	setData,
} = useDetail();
const activeNames = ref(['1', '2', '3', '4', '5']);
const basicInfoRef = ref();
const demandListRef = ref();
const sceneListRef = ref();
const reformListRef = ref();
const fileListRef = ref();
//提交
const startRef = ref();
const handleSubmit = (operationType: string) => {
	const requestParams = setRequestParams(operationType);
	const loading = ElLoading.service({
		lock: true,
		text: '提交中...',
	});
	threeListSubmitApi(requestParams)
		.then((res) => {
			return getDetail(res.threeListId);
		})
		.then((detailData: any) => {
			if (operationType === '1' || operationType === '3') {
				ElMessage.success('保存成功');
			}
			//修改提交
			if (operationType === '4') {
				ElMessage.success('提交成功');
				submitPass();
			}
			//申报
			if (operationType === '2') {
				startRef.value.handle({
					flowName: flowName.THREE_LIST,
					businessKey: detailData.threeListId,
				});
			}
		})
		.finally(() => {
			loading.close();
		});
};
//设置参数 1  申报之前保存  2 做申报操作  3 复制
const setRequestParams = (operationType: string) => {
	const basicInfo = basicInfoRef.value.getData();
	const demandList = demandListRef.value.getData();
	const reformListList = reformListRef.value.getData();
	const threeListFile = fileListRef.value.getData();
	const sceneList = sceneListRef.value.getData();
	//未通过的流程，是发起一笔新的流程，threeListId threeListCode 传空
	if (basicInfo.formData.threeListStatus === '6') {
		basicInfo.formData.threeListId = null;
		basicInfo.formData.threeListCode = null;
	}
	//建设类型变成字符串
	const constructType = basicInfo.formData.constructType.toString();
	return {
		...basicInfo.formData,
		constructType,
		operationType,
		integratedApplicationList: basicInfo.arrayFormData,
		demandList,
		reformListList,
		threeListFile,
		sceneCoreList: sceneList.sceneCoreList,
		sceneLevelFunction: sceneList.sceneLevelFunction,
		sceneOneLevelList: sceneList.sceneOneLevelList,
	};
};
// 定义一个函数来执行检查和报告错误
const checkAndReportError = async (checkFunction: any, errorMessage: string) => {
	try {
		return await checkFunction();
	} catch (error) {
		ElMessage.error(errorMessage);
		return false;
	}
};
//申报
const handleCheck = async (operationType: string) => {
	// 执行检查和报告错误的逻辑
	const basicResult = await checkAndReportError(basicInfoRef.value.check, '基本信息填写错误');
	if (!basicResult) return;
	const demandResult = await checkAndReportError(demandListRef.value.check, '需求清单填写错误');
	if (!demandResult) return;
	const sceneResult = await checkAndReportError(sceneListRef.value.check, '场景清单填写错误');
	if (!sceneResult) return;
	const reformResult = await checkAndReportError(reformListRef.value.check, '改革清单填写错误');
	if (!reformResult) return;
	const fileResult = await checkAndReportError(fileListRef.value.check, '附件清单填写错误');
	if (!fileResult) return;
	handleSubmit(operationType);
};
//一键填写
const oneInput = (operationType: string) => {
	const data = {
		operationType,
		threeListId: null,
		threeListCode: null,
		threeListName: 'y20240726007测试',
		applicationCode: 'A00000001202407261630530000118971',
		threeListStatus: '1',
		responsibleDeptName: '全国',
		responsibleDept: '3',
		headName: '李奎大将军1',
		headPhone: '19909090909',
		belongDomain: '5',
		deployPorts: '3',
		isWorkTeam: '1',
		budgetAmount: 1000,
		constructType: '3,2',
		existingApplicationName: '数字重庆',
		specialTeamFormation: '无',
		belongingRunway: '55',
		runwayName: null,
		teamLeaderUnit: '5',
		integratedApplicationList: [
			{
				integratedApplicationId: 531,
				threeListId: 1,
				integratedApplicationName: '智慧招联',
				competentDepartment: '营销',
				remark: null,
				createBy: 'admin',
				createTime: '2024-07-27 09:52:26',
				updateBy: null,
				updateTime: null,
			},
			{
				integratedApplicationId: 532,
				threeListId: 1,
				integratedApplicationName: '智慧招商',
				competentDepartment: '人力',
				remark: null,
				createBy: 'admin',
				createTime: '2024-07-27 09:52:26',
				updateBy: null,
				updateTime: null,
			},
		],
		demandList: {
			demandListTypes: ['1', '2'],
			partyDecisionDemandList: [
				{
					partyDecisionDemandId: 428,
					decisionDemandType: '9',
					demandContent: '要求',
					fileId: '1817010238100254722',
					fileIdList: [
						{
							fileId: '1817010238100254722',
							appCode: '99              ',
							type: '99',
							name: '图片3.png',
							url: '/api//admin/sys-file/oss/file?fileName=7ac6ad4f9a184819b4b5b9a2b5191806.png',
							createBy: 'admin',
							createTime: '2024-07-27 09:33:05',
							id: '1817010238100254722',
							uid: 1722045172442,
							status: 'success',
						},
					],
					remark: null,
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					updateBy: null,
					updateTime: null,
					threeListId: 1,
				},
			],
			cityGovernmentDemandList: [
				{
					cityGovernmentDemandId: 167,
					cityGovernmentDemandType: '5',
					cityGovernmentDemandTypeName: '市政府常务会会议部署事项',
					demandContent: '数字重庆',
					fileId: '1817010280739549185',
					fileIdList: [
						{
							fileId: '1817010280739549185',
							appCode: '99              ',
							type: '99',
							name: '图片5.png',
							url: '/api//admin/sys-file/oss/file?fileName=660ff7c81a5340fa99085187db2cfb40.png',
							createBy: 'admin',
							createTime: '2024-07-27 09:33:05',
							id: '1817010280739549185',
							uid: 1722045172446,
							status: 'success',
						},
					],
					remark: null,
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					updateBy: null,
					updateTime: null,
					threeListId: 1,
				},
			],
		},
		reformListList: [
			{
				reformListId: 576,
				reformMatters: '改革清单',
				specificMeasures: '措施及成效',
				remark: null,
				createBy: 'admin',
				createTime: '2024-07-27 09:52:27',
				updateBy: null,
				updateTime: null,
				threeListId: 1,
			},
			{
				reformListId: 577,
				reformMatters: '改革清单2',
				specificMeasures: '措施及成效2',
				remark: null,
				createBy: 'admin',
				createTime: '2024-07-27 09:52:27',
				updateBy: null,
				updateTime: null,
				threeListId: 1,
			},
		],
		threeListFile: {
			threeListFileId: 301,
			officialDocuments: '1817015092107763714',
			officialDocumentsFileIdList: [
				{
					fileId: '1817015092107763714',
					appCode: '99              ',
					type: '99',
					name: '1.pdf',
					url: '/api//admin/sys-file/oss/file?fileName=e3f0195c2b6843cab3a75855714382fc.pdf',
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					id: '1817015092107763714',
					uid: 1722045172301,
					status: 'success',
				},
			],
			threeList: '1817015102568357889',
			threeListFileIdList: [
				{
					fileId: '1817015102568357889',
					appCode: '99              ',
					type: '99',
					name: '项目.docx',
					url: '/api//admin/sys-file/oss/file?fileName=4d1362736e294853aa8f47ee029dd79f.docx',
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					id: '1817015102568357889',
					uid: 1722045172315,
					status: 'success',
				},
			],
			integrationDiagram: '1817015115012857857',
			integrationDiagramFileIdList: [
				{
					fileId: '1817015115012857857',
					appCode: '99              ',
					type: '99',
					name: '图片5.png',
					url: '/api//admin/sys-file/oss/file?fileName=b00dce27be7643a1a372f7028dd1214d.png',
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					id: '1817015115012857857',
					uid: 1722045172317,
					status: 'success',
				},
			],
			requirementsDiagrams: '1817015128312995841,1817015150098210818',
			requirementsDiagramsFileIdList: [
				{
					fileId: '1817015128312995841',
					appCode: '99              ',
					type: '99',
					name: '图片2.png',
					url: '/api//admin/sys-file/oss/file?fileName=262f2768bcd34c74b3dc969ff03b9514.png',
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					id: '1817015128312995841',
					uid: 1722045172324,
					status: 'success',
				},
				{
					fileId: '1817015150098210818',
					appCode: '99              ',
					type: '99',
					name: '图片1.png',
					url: '/api//admin/sys-file/oss/file?fileName=e6d00a67f13a4c8f9f2243f7161e531b.png',
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					id: '1817015150098210818',
					uid: 1722045172325,
					status: 'success',
				},
			],
			architectureDiagram: '1817015138308022274',
			architectureDiagramFileIdList: [
				{
					fileId: '1817015138308022274',
					appCode: '99              ',
					type: '99',
					name: '图片4.png',
					url: '/api//admin/sys-file/oss/file?fileName=49b75831843240718206b5e5df17ee4f.png',
					createBy: 'admin',
					createTime: '2024-07-27 09:52:26',
					id: '1817015138308022274',
					uid: 1722045172328,
					status: 'success',
				},
			],
			remark: null,
			createBy: 'admin',
			createTime: '2024-07-27 09:52:27',
			updateBy: null,
			updateTime: null,
			threeListId: 1,
		},
		sceneCoreList: [
			{
				sceneCoreId: 530,
				coreBusiness: '核心业务',
				lastFlowDescription: '原流程图描述',
				nowFlowDescription: '现流程图描述',
				simpFlowDescription: '精简流程、压缩环节情况描述',
				flowImageFileId: '1817014311098998786',
				flowImageFileIdList: [
					{
						fileId: '1817014311098998786',
						appCode: '99              ',
						type: '99',
						name: '图片2.png',
						url: '/api//admin/sys-file/oss/file?fileName=37391410de1d456590feaaea17f8994f.png',
						createBy: 'admin',
						createTime: '2024-07-27 09:49:59',
						id: '1817014311098998786',
						uid: 1722045172435,
						status: 'success',
					},
				],
				remark: null,
				createBy: 'admin',
				createTime: '2024-07-27 09:52:26',
				updateBy: null,
				updateTime: null,
				threeListId: 1,
			},
		],
		sceneLevelFunction: {
			serviceObject: '服务端（业务申请方综述）',
			sceneLevelFunctionId: 314,
			sceneLevelFunctionManageList: [
				{
					sceneLevelFunctionManageId: 565,
					manageClient: '4',
					manageClientName: '镇街',
					function: '功能1',
					sceneLevelFunctionId: 314,
					remark: null,
					createBy: 'admin',
					createTime: '2024-07-27 09:52:27',
					updateBy: null,
					updateTime: null,
				},
				{
					sceneLevelFunctionManageId: 566,
					manageClient: '4',
					manageClientName: '镇街',
					function: '功能2',
					sceneLevelFunctionId: 314,
					remark: null,
					createBy: 'admin',
					createTime: '2024-07-27 09:52:27',
					updateBy: null,
					updateTime: null,
				},
			],
		},
		sceneOneLevelList: [
			{
				firstId: '10221d6d-f2a4-44e5-858c-5ce92f3f9ebb',
				sceneOneLevelName: '一级场景名称',
				businessCollaboration: '多跨业务协同',
				dataSharing: '多跨数据共享',
				sceneTwoLevelList: [
					{
						sceneTwoLevelListId: '',
						sceneTwoLevelName: '二级场景名称',
						presetFunction: '预设功能',
						dataSources: '2,1',
						dataResourceName: '资源名称',
						serviceClient: '服务端（业务申请方）',
						secondId: 'b272c494-34a5-4621-b5d5-5c5fd186bac6',
						sceneSystemDockingList: [
							{ sourceId: 'de47492f-3245-4cdf-a9a9-b2bc0de56752', managerUnit: '主营单位', systemName: '系统名称', dataResourceName: '资源名称' },
							{ sourceId: '91269612-ee84-4346-82f7-5e79759b451f', managerUnit: '主营单位1', systemName: '系统名称1', dataResourceName: '资源名称1' },
						],
						businessAcceptancePartyList: [
							{ menageId: '211ddceb-acf5-4980-95eb-fd3740008f5c', involveLevel: '3', involveDepart: '部门', responsibilitiesFulfilled: '职责' },
						],
					},
					{
						sceneTwoLevelListId: '',
						sceneTwoLevelName: '二级场景名称2',
						presetFunction: '预设功能2',
						dataSources: '2,1',
						dataResourceName: '资源名称2',
						serviceClient: '服务端（业务申请方）',
						secondId: 'b272c494-34a5-4621-b5d5-5c5fd186bac6',
						sceneSystemDockingList: [
							{ sourceId: '580ba2f2-e81d-4559-acee-32e4fbe1ef33', managerUnit: '主营单位2', systemName: '系统名称2', dataResourceName: '资源名称2' },
						],
						businessAcceptancePartyList: [
							{ menageId: '9b40b4ed-376f-4fd6-8bdd-d9f94266a0d8', involveLevel: '3', involveDepart: '部门', responsibilitiesFulfilled: '职责' },
						],
					},
				],
			},
		],
	};
	setData(data);
};
//申请修改
const editListRef = ref();
const handleEdit = () => {
	editListRef.value.dialogVisible = true;
};
//审核
const examineBoxRef = ref();
const handleApprove = () => {
	examineBoxRef.value.handle({
		processInstanceId: processInstanceId,
	});
};
//审批人撤回
const handleApprovalCancel = () => {
	const { handleApprovalCancel } = useOperate(routerParams.value);
	handleApprovalCancel(submitPass);
};
// 辅助函数：根据环境返回不同的按钮数据
function getButtonDataBasedOnEnv() {
	const env = import.meta.env.PROD;
	return env
		? [
				{ name: '保存', click: () => handleSubmit('1'), class: 'white-button' },
				{ name: '申报', click: () => handleCheck('2'), class: 'blue-button' },
		  ]
		: [
				{ name: '保存', click: () => handleSubmit('1'), class: 'white-button' },
				{ name: '申报', click: () => handleCheck('2'), class: 'blue-button' },
				{ name: '一键填写', click: () => oneInput('1') },
		  ];
}
//设置操作按钮/流程信息显示隐藏/表单是否可提交
const scheduleAndHistoryShow = ref(false);
const buttonData = computed(() => {
	const { routerGo, handleCancel, handleDelete } = useOperate(routerParams.value);
	const { operateType = '' } = routerParams.value;
	// 初始化按钮数据和显示状态
	let buttons: any = [];
	let showHistory = false;
	let formTypeValue = 'submit';
	//新增
	if (operateType === 'add') {
		showHistory = false;
		buttons = getButtonDataBasedOnEnv();
		formTypeValue = 'submit';
	}
	//查看
	if (operateType === 'view') {
		switch (basicInfoData.value.threeListStatus) {
			//待申报：点击编辑和申报，调到对应的页面
			case '1':
				showHistory = false;
				buttons = [
					{ name: '编辑', click: () => routerGo('edit'), class: 'white-button' },
					{ name: '申报', click: () => routerGo('declare'), class: 'blue-button' },
					{ name: '删除', click: () => handleDelete(submitPass), class: 'red-button' },
				];
				break;
			case '6':
				buttons = [
					{ name: '编辑', click: () => routerGo('edit'), class: 'white-button' },
					{ name: '申报', click: () => routerGo('declare'), class: 'blue-button' },
					{ name: '删除', click: () => handleDelete(submitPass), class: 'red-button' },
				];
				showHistory = true;
				break;
			//申报中
			case '2':
				buttons = [{ name: '申请修改', click: () => handleEdit(), class: 'blue-button' }];
				if (isCancel.value) {
					buttons.unshift({ name: '撤消', click: () => handleCancel(submitPass), class: 'red-button' });
				}
				showHistory = true;
				break;
			//修改中
			case '4':
				buttons = [{ name: '修改', click: () => routerGo('declare'), class: 'white-button' }];
				showHistory = true;
				break;
			// 3 资料修改申请中  5 已通过
			case '3':
			case '5':
				buttons = [];
				showHistory = true;
				break;
			default:
				break;
		}
		formTypeValue = 'view';
	}
	//修改/申报/修改申请
	if (operateType === 'edit' || operateType === 'declare') {
		switch (basicInfoData.value.threeListStatus) {
			//状态为待申报，不显示历史
			case '1':
				showHistory = false;
				buttons = getButtonDataBasedOnEnv();
				formTypeValue = 'submit';
				break;
			//申报中，点击修改申请
			case '2':
				showHistory = false;
				buttons = [{ name: '申请修改', click: () => handleEdit(), class: 'blue-button' }];
				if (isCancel.value) {
					buttons.unshift({ name: '撤销', click: () => handleCancel(submitPass), class: 'red-button' });
				}
				formTypeValue = 'view';
				break;
			//修改中
			case '4':
				showHistory = true;
				buttons = [
					{ name: '保存', click: () => handleSubmit('3'), class: 'white-button' },
					{ name: '提交', click: () => handleCheck('4'), class: 'blue-button' },
				];
				formTypeValue = 'submit';
				break;
			//未通过，复制一份新的发起
			case '6':
				showHistory = true;
				buttons = getButtonDataBasedOnEnv();
				formTypeValue = 'submit';
				break;
			default:
				break;
		}
	}
	//审批
	if (operateType === 'audit') {
		//待审核
		switch (routerParams.value.processStatus) {
			case '1':
				buttons = [{ name: '审核', click: () => handleApprove(), class: 'blue-button' }];
				break;
			//已通过
			case '2':
				if (isReturn.value) {
					buttons = [{ name: '撤回', click: () => handleApprovalCancel(), class: 'red-button' }];
				} else {
					buttons = [];
				}
				break;
			default:
				buttons = [];
				break;
		}
		formTypeValue = 'view';
		showHistory = true;
	}
	//历史
	if (operateType === 'history') {
		formTypeValue = 'view';
	}
	// 设置响应式数据
	scheduleAndHistoryShow.value = showHistory;
	formType.value = formTypeValue;
	return buttons;
});

//资料修改发起
const getFileEditValue = (value: any) => {
	startRef.value.handle({
		flowName: flowName.FILE_EDIT,
		businessKey: value.businessKey,
	});
};
const submitPass = () => {
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
};
</script>
<style scoped lang="scss"></style>
